
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>地图绘制与编辑工具</title>
    <!-- 引入 Leaflet 核心库 -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <!-- 引入 Leaflet.Draw 绘图插件 -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.css">
    <script src="https://unpkg.com/leaflet-draw@1.0.4/dist/leaflet.draw.js"></script>
    <!-- 引入 html2canvas 和 jsPDF 用于导出 PDF -->
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <!-- 天地图密钥（需替换为自己的，可去天地图官网申请） -->
    <style>
        /* 页面布局 */
        body {
            display: flex;
            margin: 0;
            padding: 0;
            font-family: "微软雅黑", sans-serif;
        }

        /* 左侧编辑栏 */
        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #dee2e6;
            padding: 20px;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow-y: auto;
        }

        .sidebar h2 {
            margin: 0 0 20px 0;
            font-size: 18px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            transition: border-color 0.2s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }

        .form-group .color-picker {
            display: flex;
            gap: 5px;
        }

        .form-group .color-picker div {
            width: 24px;
            height: 24px;
            border: 1px solid #ccc;
            border-radius: 4px;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .form-group .color-picker div:hover {
            transform: scale(1.1);
        }

        .element-list {
            margin-top: 20px;
            flex-grow: 1;
            overflow-y: auto;
        }

        .element-list h3 {
            font-size: 16px;
            margin-bottom: 10px;
        }

        .element-list ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .element-list li {
            padding: 10px;
            border: 1px solid #eee;
            margin-bottom: 5px;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.2s;
        }

        .element-list li:hover {
            background: #f1f1f1;
        }

        .element-list li.active {
            background: #e9ecef;
            border-color: #007bff;
        }

        .btn-delete {
            color: #dc3545;
            font-size: 16px;
            cursor: pointer;
            transition: color 0.2s;
        }

        .btn-delete:hover {
            color: #c82333;
        }

        /* 右侧地图容器 */
        #map {
            flex-grow: 1;
            height: 100vh;
        }

        /* 绘图控件样式调整 */
        .leaflet-draw-toolbar a {
            color: #333;
        }

        /* 地图上的地块样式 */
        .leaflet-interactive {
            cursor: pointer;
        }

        /* 模式切换按钮 */
        .mode-switch {
            display: flex;
            margin-bottom: 20px;
        }

        .mode-switch button {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ccc;
            background-color: #f8f9fa;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .mode-switch button.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .action-btn {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .action-btn:hover {
            background: #5a6268;
        }

        /* 导出按钮 */
        .export-btn {
            margin-top: 15px;
            padding: 10px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .export-btn:hover {
            background-color: #218838;
        }

        /* 自定义tooltip样式，让文字自适应地块 */
        .leaflet-tooltip.custom-tooltip {
            background: rgba(255, 255, 255, 0.9);
            border: 1px solid #ccc;
            box-shadow: 0 1px 3px rgba(0, 0, 100, 0.4);
            padding: 8px;
            white-space: normal;
            max-width: 200px;
            word-wrap: break-word;
        }
    </style>
</head>

<body>
    <!-- 左侧编辑栏 -->
    <div class="sidebar">
        <div class="mode-switch">
            <button id="mode-tianditu" class="active">天地图模式</button>
            <button id="mode-image">图片模式</button>
        </div>

        <div id="tianditu-settings" class="form-group">
            <label for="tdt-key">天地图密钥</label>
            <input type="text" id="tdt-key" placeholder="输入密钥后自动加载">
        </div>
        <div id="image-settings" class="form-group" style="display:none;">
            <label for="image-url">图片链接</label>
            <input type="text" id="image-url" value="https://ts1.tc.mm.bing.net/th/id/OIP-C.Jowy4ywmGSEFuS4RukTmxgHaFL?w=290&h=215&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2">
            <button id="load-image" class="action-btn">加载图片</button>
        </div>

        <h2>元素属性</h2>
        <!-- 地块属性表单 -->
        <div class="form-group">
            <label for="name">地块名称</label>
            <input type="text" id="name" placeholder="输入地块名称">
        </div>
        <div class="form-group">
            <label for="type">地块类型</label>
            <input type="text" id="type" placeholder="如：玉米田、大棚">
        </div>
        <div class="form-group">
            <label for="area">地块面积</label>
            <input type="text" id="area" placeholder="如：10亩、100㎡">
        </div>
        <div class="form-group">
            <label>描边颜色</label>
            <div class="color-picker" id="strokeColorPicker">
                <div style="background: #007bff"></div>
                <div style="background: #28a745"></div>
                <div style="background: #dc3545"></div>
                <div style="background: #ffc107"></div>
                <div style="background: #17a2b8"></div>
            </div>
            <input type="number" id="strokeWidth" value="3" min="1" max="10" placeholder="宽度" style="margin-top:5px;">
        </div>
        <div class="form-group">
            <label>背景颜色</label>
            <div class="color-picker" id="fillColorPicker">
                <div style="background: rgba(0,123,255,0.2)"></div>
                <div style="background: rgba(40,167,69,0.2)"></div>
                <div style="background: rgba(220,53,69,0.2)"></div>
                <div style="background: rgba(255,193,7,0.2)"></div>
                <div style="background: rgba(23,162,184,0.2)"></div>
            </div>
            <input type="number" id="fillOpacity" value="0.2" step="0.1" min="0" max="1" placeholder="透明度"
                style="margin-top:5px;">
        </div>
        <div class="form-group">
            <label>文字颜色</label>
            <div class="color-picker" id="textColorPicker">
                <div style="background: #000"></div>
                <div style="background: #fff"></div>
                <div style="background: #007bff"></div>
                <div style="background: #28a745"></div>
            </div>
            <input type="number" id="textSize" value="14" min="8" max="36" placeholder="文字大小" style="margin-top:5px;"
                title="调整地块上显示的文字大小">
        </div>

        <button class="export-btn" id="exportPDF">导出PDF</button>

        <!-- 元素列表 -->
        <div class="element-list">
            <h3>元素列表</h3>
            <ul id="elementList"></ul>
        </div>
    </div>

    <!-- 右侧地图容器 -->
    <div id="map"></div>

    <script>
        // 初始化地图
        const map = L.map('map').setView([34.05, 108.2], 5);

        // 存储当前模式：tianditu 或 image
        let currentMode = 'tianditu';

        // 存储图层数据，用于模式切换时保留
        let layerData = [];

        // 天地图图层 (初始为 null)
        let tiandituLayer = null;

        // 图片图层配置 (初始为 null)
        let imageLayer = null;
        let imageBounds = null;

        // 默认添加一个空的图层组，避免报错
        L.featureGroup().addTo(map);

        // 创建用于存储绘制图形的图层组
        const drawnLayers = L.featureGroup().addTo(map);

        // 初始化绘图控件
        const drawControl = new L.Control.Draw({
            draw: {
                polygon: {
                    shapeOptions: { color: '#007bff' },
                    allowIntersection: false, // 禁止多边形交叉
                    drawError: {
                        color: '#e1e100',
                        message: '绘制的多边形不能交叉！'
                    },
                    showArea: true // 显示面积
                },
                marker: false,
                polyline: {
                    shapeOptions: { color: '#28a745' }
                },
                rectangle: {
                     shapeOptions: { color: '#dc3545' }
                },
                circle: {
                     shapeOptions: { color: '#ffc107' }
                }
            },
            edit: {
                featureGroup: drawnLayers,
                remove: true
            }
        }).addTo(map);

        // 存储当前选中的地块
        let currentLayer = null;

        // 绘图完成事件
        map.on(L.Draw.Event.CREATED, function (e) {
            const layer = e.layer;
            const type = e.layerType;

            // 为图层添加自定义属性
            layer.properties = {
                name: "未命名地块",
                type: "",
                area: "",
                strokeColor: "#007bff",
                strokeWidth: 3,
                fillColor: "rgba(0,123,255,0.2)",
                fillOpacity: 0.2,
                textColor: "#000",
                textSize: 14,
                shapeType: type
            };

            // 根据图形类型设置默认样式
            if(type === 'polyline') {
                layer.properties.strokeColor = '#28a745';
                layer.setStyle({ color: '#28a745' });
            } else if (type === 'rectangle') {
                layer.properties.strokeColor = '#dc3545';
                layer.properties.fillColor = 'rgba(220,53,69,0.2)';
                layer.setStyle({ color: '#dc3545', fillColor: 'rgba(220,53,69,0.2)' });
            } else if (type === 'circle') {
                layer.properties.strokeColor = '#ffc107';
                layer.properties.fillColor = 'rgba(255,193,7,0.2)';
                layer.setStyle({ color: '#ffc107', fillColor: 'rgba(255,193,7,0.2)' });
            }

            // 添加到绘制图层组
            drawnLayers.addLayer(layer);

            // 保存图层数据
            saveLayerData(layer);

            // 添加到元素列表
            addToElementList(layer);

            // 选中当前图层
            selectLayer(layer);

            // 计算并设置面积/长度/半径
            updateMeasurement(layer);
            updateLayerTooltip(layer);
        });

        // 编辑完成事件 - 确保编辑后属性保持一致
        map.on(L.Draw.Event.EDITED, function (e) {
            const layers = e.layers;
            layers.eachLayer(function (layer) {
                // 更新图层数据
                saveLayerData(layer);

                // 重新计算面积
                updateMeasurement(layer);
                if (currentLayer === layer) {
                    document.getElementById('area').value = layer.properties.area;
                }
                updateLayerTooltip(layer);
            });
        });

        // 删除完成事件
        map.on(L.Draw.Event.DELETED, function (e) {
            // 更新图层数据
            const layers = e.layers;
            layers.eachLayer(function (layer) {
                removeLayerData(layer._leaflet_id);
                removeFromElementList(layer);
                if (currentLayer === layer) {
                    currentLayer = null;
                    resetForm();
                }
            });
        });

        // 左侧表单 - 名称输入事件
        document.getElementById('name').addEventListener('input', function (e) {
            if (currentLayer) {
                currentLayer.properties.name = e.target.value;
                updateLayerTooltip(currentLayer);
                updateElementList(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 类型输入事件
        document.getElementById('type').addEventListener('input', function (e) {
            if (currentLayer) {
                currentLayer.properties.type = e.target.value;
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 面积输入事件
        document.getElementById('area').addEventListener('input', function (e) {
            if (currentLayer) {
                currentLayer.properties.area = e.target.value;
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 描边颜色选择
        document.getElementById('strokeColorPicker').addEventListener('click', function (e) {
            if (e.target.tagName === 'DIV' && currentLayer) {
                const color = e.target.style.background;
                currentLayer.properties.strokeColor = color;
                currentLayer.setStyle({ color: color });
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 描边宽度调整
        document.getElementById('strokeWidth').addEventListener('input', function (e) {
            if (currentLayer) {
                const width = parseInt(e.target.value);
                currentLayer.properties.strokeWidth = width;
                currentLayer.setStyle({ weight: width });
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 背景颜色选择
        document.getElementById('fillColorPicker').addEventListener('click', function (e) {
            if (e.target.tagName === 'DIV' && currentLayer) {
                const color = e.target.style.background;
                currentLayer.properties.fillColor = color;
                currentLayer.setStyle({ fillColor: color });
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 背景透明度调整
        document.getElementById('fillOpacity').addEventListener('input', function (e) {
            if (currentLayer) {
                const opacity = parseFloat(e.target.value);
                currentLayer.properties.fillOpacity = opacity;
                currentLayer.setStyle({ fillOpacity: opacity });
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 文字颜色选择
        document.getElementById('textColorPicker').addEventListener('click', function (e) {
            if (e.target.tagName === 'DIV' && currentLayer) {
                const color = e.target.style.background;
                currentLayer.properties.textColor = color;
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 左侧表单 - 文字大小调整
        document.getElementById('textSize').addEventListener('input', function (e) {
            if (currentLayer) {
                const size = parseInt(e.target.value);
                currentLayer.properties.textSize = size;
                updateLayerTooltip(currentLayer);
                saveLayerData(currentLayer);
            }
        });

        // 元素列表 - 点击选中图层
        document.getElementById('elementList').addEventListener('click', function (e) {
            if (e.target.tagName === 'LI') {
                const layerId = e.target.dataset.layerId;
                // 查找对应的图层
                drawnLayers.eachLayer(function (layer) {
                    if (layer._leaflet_id === parseInt(layerId)) {
                        selectLayer(layer);
                        return false;
                    }
                });
            }
        });

        // 元素列表 - 删除按钮
        document.getElementById('elementList').addEventListener('click', function (e) {
            if (e.target.classList.contains('btn-delete')) {
                e.stopPropagation();
                const layerId = e.target.parentElement.dataset.layerId;
                // 删除图层
                drawnLayers.eachLayer(function (layer) {
                    if (layer._leaflet_id === parseInt(layerId)) {
                        drawnLayers.removeLayer(layer);
                        removeLayerData(layer._leaflet_id);
                        removeFromElementList(layer);
                        if (currentLayer === layer) {
                            currentLayer = null;
                            resetForm();
                        }
                        return false;
                    }
                });
            }
        });

        // 点击地图其他区域取消选中
        map.on('click', function(e) {
            if (e.target === map) {
                unselectAllLayers();
            }
        });

        // 点击地块选中
        map.on('click', function(e) {
            if (e.layer && drawnLayers.hasLayer(e.layer)) {
                selectLayer(e.layer);
            }
        });

        // 模式切换
        document.getElementById('mode-tianditu').addEventListener('click', function() {
            switchMode('tianditu');
        });
        
        document.getElementById('mode-image').addEventListener('click', function() {
            switchMode('image');
        });

        // 天地图密钥输入事件
        document.getElementById('tdt-key').addEventListener('input', function(e) {
            if (currentMode === 'tianditu') {
                loadTianDiTuLayer(e.target.value);
            }
        });

        // 加载图片按钮事件
        document.getElementById('load-image').addEventListener('click', function() {
            const imageUrl = document.getElementById('image-url').value;
            loadImageView(imageUrl);
        });
        
        // 导出PDF
        document.getElementById('exportPDF').addEventListener('click', exportPDF);

        // ---------- 工具函数 ----------
        // 加载天地图图层
        function loadTianDiTuLayer(key) {
            if (!key) {
                if(tiandituLayer) map.removeLayer(tiandituLayer);
                return;
            };

            const tdtUrl = `https://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${key}`;
            
            if (tiandituLayer) {
                tiandituLayer.setUrl(tdtUrl);
            } else {
                tiandituLayer = L.tileLayer(tdtUrl, {
                    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
                    attribution: "天地图"
                });
            }
            if (!map.hasLayer(tiandituLayer)) {
                tiandituLayer.addTo(map);
            }
             map.setView([34.05, 108.2], 5);
        }

        // 加载图片视图
        function loadImageView(imageUrl) {
             if (!imageUrl) {
                alert('请输入图片链接！');
                return;
            }

            const img = new Image();
            img.onload = function() {
                if(imageLayer) map.removeLayer(imageLayer);

                const { width, height } = this;
                imageBounds = [[0, 0], [height, width]];
                
                imageLayer = L.imageOverlay(imageUrl, imageBounds);
                imageLayer.addTo(map);
                
                map.fitBounds(imageBounds);
            };
            img.onerror = function() {
                alert('图片加载失败，请检查链接是否正确。');
            };
            img.src = imageUrl;
        }

        // 模式切换
        function switchMode(mode) {
            if (currentMode === mode) return;
            
            // 保存当前图层状态
            saveAllLayerData();
            
            // 切换时移除当前底图
            if (currentMode === 'tianditu' && tiandituLayer) {
                map.removeLayer(tiandituLayer);
            } else if (currentMode === 'image' && imageLayer) {
                map.removeLayer(imageLayer);
            }
            
            // 切换图层
            if (mode === 'tianditu') {
                const key = document.getElementById('tdt-key').value;
                if(key) loadTianDiTuLayer(key);
                map.setView([34.05, 108.2], 5);
                map.setMaxBounds(null); // 解除边界限制
                document.getElementById('tianditu-settings').style.display = 'block';
                document.getElementById('image-settings').style.display = 'none';
                document.getElementById('mode-tianditu').classList.add('active');
                document.getElementById('mode-image').classList.remove('active');
            } else {
                if (imageLayer) {
                    imageLayer.addTo(map);
                    map.fitBounds(imageBounds);
                }
                document.getElementById('tianditu-settings').style.display = 'none';
                document.getElementById('image-settings').style.display = 'block';
                document.getElementById('mode-image').classList.add('active');
                document.getElementById('mode-tianditu').classList.remove('active');
            }
            
            // 恢复绘制的图层
            restoreAllLayers();
            
            // 更新当前模式
            currentMode = mode;
        }
        
        // 保存单个图层数据
        function saveLayerData(layer) {
            // 查找是否已存在该图层数据
            const index = layerData.findIndex(item => item.id === layer._leaflet_id);
            
            // 提取图层数据
            const data = {
                id: layer._leaflet_id,
                properties: layer.properties,
            };

            if (layer instanceof L.Circle) {
                data.type = 'circle';
                data.latlng = layer.getLatLng();
                data.radius = layer.getRadius();
            } else if (layer instanceof L.Polygon) { // 包括矩形
                data.type = 'polygon';
                data.latlngs = layer.getLatLngs();
            } else if (layer instanceof L.Polyline) {
                data.type = 'polyline';
                data.latlngs = layer.getLatLngs();
            }
            
            if (index !== -1) {
                // 更新已有数据
                layerData[index] = data;
            } else {
                // 添加新数据
                layerData.push(data);
            }
        }
        
        // 保存所有图层数据
        function saveAllLayerData() {
            layerData = [];
            drawnLayers.eachLayer(function(layer) {
                saveLayerData(layer);
            });
        }
        
        // 移除图层数据
        function removeLayerData(layerId) {
            layerData = layerData.filter(item => item.id !== layerId);
        }
        
        // 恢复所有图层
        function restoreAllLayers() {
            // 清除当前所有图层
            drawnLayers.clearLayers();
            
            // 重新添加图层
            layerData.forEach(data => {
                let layer;
                const options = {
                    color: data.properties.strokeColor,
                    weight: data.properties.strokeWidth,
                    fillColor: data.properties.fillColor,
                    fillOpacity: data.properties.fillOpacity
                };
                
                if (data.type === 'polygon') {
                    layer = L.polygon(data.latlngs, options);
                } else if (data.type === 'polyline'){
                    layer = L.polyline(data.latlngs, options);
                } else if (data.type === 'circle') {
                    layer = L.circle(data.latlng, { ...options, radius: data.radius });
                }
                
                if (layer) {
                    // 设置属性
                    layer.properties = data.properties;
                    
                    // 添加到图层组
                    drawnLayers.addLayer(layer);
                    
                    // 添加到元素列表
                    addToElementList(layer);
                    
                    // 更新 tooltip
                    updateLayerTooltip(layer);
                }
            });
        }
        
        // 添加图层到元素列表
        function addToElementList(layer) {
            const list = document.getElementById('elementList');
            const li = document.createElement('li');
            li.dataset.layerId = layer._leaflet_id;

            const typeMap = {
                polygon: '多边形',
                rectangle: '矩形',
                polyline: '线段',
                circle: '圆形'
            };
            const shapeName = typeMap[layer.properties.shapeType] || '图形';

            li.innerHTML = `
                [${shapeName}] ${layer.properties.name}
                <span class="btn-delete">&times;</span>
            `;
            list.appendChild(li);
        }

        // 更新元素列表
        function updateElementList(layer) {
            const listItems = document.querySelectorAll('#elementList li');
            listItems.forEach(function (li) {
                if (li.dataset.layerId == layer._leaflet_id) {
                    const typeMap = {
                        polygon: '多边形',
                        rectangle: '矩形',
                        polyline: '线段',
                        circle: '圆形'
                    };
                    const shapeName = typeMap[layer.properties.shapeType] || '图形';
                    li.innerHTML = `
                        [${shapeName}] ${layer.properties.name}
                        <span class="btn-delete">&times;</span>
                    `;
                }
            });
        }

        // 从元素列表移除
        function removeFromElementList(layer) {
            const listItems = document.querySelectorAll('#elementList li');
            listItems.forEach(function (li) {
                if (li.dataset.layerId == layer._leaflet_id) {
                    li.remove();
                }
            });
        }

        // 选中图层
        function selectLayer(layer) {
            // 取消之前选中的样式
            unselectAllLayers();
            
            // 设置当前选中样式
            const listItems = document.querySelectorAll('#elementList li');
            listItems.forEach(function (li) {
                if (li.dataset.layerId == layer._leaflet_id) {
                    li.classList.add('active');
                }
            });
            
            // 高亮显示当前选中的图层
            layer.setStyle({
                weight: layer.properties.strokeWidth + 2,
                opacity: 1
            });
            
            // 更新表单数据
            currentLayer = layer;
            document.getElementById('name').value = layer.properties.name;
            document.getElementById('type').value = layer.properties.type;
            document.getElementById('area').value = layer.properties.area;
            document.getElementById('strokeWidth').value = layer.properties.strokeWidth;
            document.getElementById('fillOpacity').value = layer.properties.fillOpacity;
            document.getElementById('textSize').value = layer.properties.textSize;
            
            // 更新图层 tooltip
            updateLayerTooltip(layer);
        }

        // 取消所有图层的选中状态
        function unselectAllLayers() {
            const listItems = document.querySelectorAll('#elementList li');
            listItems.forEach(function (li) {
                li.classList.remove('active');
            });
            
            drawnLayers.eachLayer(function (layer) {
                layer.setStyle({
                    weight: layer.properties.strokeWidth,
                    opacity: 0.7
                });
            });
            
            currentLayer = null;
            resetForm();
        }

        // 更新图层的 tooltip 内容
        function updateLayerTooltip(layer) {
            const content = `
                <div style="color: ${layer.properties.textColor}; font-size: ${layer.properties.textSize}px; font-weight: bold;">
                    ${layer.properties.name}
                    ${layer.properties.type ? `<div style="font-size: ${layer.properties.textSize * 0.8}px; font-weight: normal;">${layer.properties.type}</div>` : ''}
                    ${layer.properties.area ? `<div style="font-size: ${layer.properties.textSize * 0.8}px; font-weight: normal;">${layer.properties.area}</div>` : ''}
                </div>
            `;
            
            layer.unbindTooltip();
            layer.bindTooltip(content, { 
                permanent: true, 
                direction: 'center',
                className: 'custom-tooltip'
            }).openTooltip();
        }

        // 重置表单
        function resetForm() {
            document.getElementById('name').value = "";
            document.getElementById('type').value = "";
            document.getElementById('area').value = "";
            document.getElementById('strokeWidth').value = 3;
            document.getElementById('fillOpacity').value = 0.2;
            document.getElementById('textSize').value = 14;
        }

        // 更新测量值
        function updateMeasurement(layer) {
            if (currentMode !== 'tianditu') {
                layer.properties.area = '仅在天地图模式下计算';
                if(currentLayer === layer) {
                    document.getElementById('area').value = layer.properties.area;
                }
                return;
            }

            const shapeType = layer.properties.shapeType;

            if (shapeType === 'polygon' || shapeType === 'rectangle') {
                const area = L.GeometryUtil.geodesicArea(layer.getLatLngs()[0]);
                layer.properties.area = formatArea(area);
            } else if (shapeType === 'polyline') {
                 const latlngs = layer.getLatLngs();
                let distance = 0;
                for (let i = 0; i < latlngs.length - 1; i++) {
                    distance += map.distance(latlngs[i], latlngs[i + 1]);
                }
                layer.properties.area = `长度: ${formatDistance(distance)}`;
            } else if (shapeType === 'circle') {
                const radius = layer.getRadius();
                layer.properties.area = `半径: ${formatDistance(radius)}`;
            }

            if (currentLayer === layer) {
                document.getElementById('area').value = layer.properties.area;
            }
        }

        // 格式化面积显示
        function formatArea(area) {
            if (area < 10000) {
                return area.toFixed(2) + ' 平方米';
            } else if (area < 1000000) {
                return (area / 10000).toFixed(2) + ' 公顷';
            } else {
                return (area / 1000000).toFixed(2) + ' 平方公里';
            }
        }
        
        // 格式化距离显示
        function formatDistance(distance) {
            if (distance < 1000) {
                return distance.toFixed(2) + ' 米';
            } else {
                return (distance / 1000).toFixed(2) + ' 公里';
            }
        }

        // 导出PDF
        function exportPDF() {
            // 保存当前地图状态
            const currentZoom = map.getZoom();
            const currentCenter = map.getCenter();
            
            // 创建一个临时容器，用于捕获地图和地块
            const exportContainer = document.createElement('div');
            exportContainer.style.width = '210mm'; // A4宽度
            exportContainer.style.height = '297mm'; // A4高度
            exportContainer.style.position = 'fixed';
            exportContainer.style.top = '-10000px';
            exportContainer.style.left = '-10000px';
            exportContainer.style.background = 'white';
            document.body.appendChild(exportContainer);
            
            // 创建一个临时地图，用于导出
            const exportMap = L.map(exportContainer, {
                center: map.getCenter(),
                zoom: map.getZoom(),
            });

            // 添加底图
            if (currentMode === 'tianditu' && tiandituLayer) {
                L.tileLayer(tiandituLayer._url, tiandituLayer.options).addTo(exportMap);
            } else if (currentMode === 'image' && imageLayer) {
                L.imageOverlay(imageLayer._url, imageLayer.getBounds()).addTo(exportMap);
            }
            
            // 添加地块
            layerData.forEach(data => {
                let layer;
                
                if (data.type === 'polygon') {
                    layer = L.polygon(data.latlngs, {
                        color: data.properties.strokeColor,
                        weight: data.properties.strokeWidth,
                        fillColor: data.properties.fillColor,
                        fillOpacity: data.properties.fillOpacity
                    });
                } else {
                    layer = L.polyline(data.latlngs, {
                        color: data.properties.strokeColor,
                        weight: data.properties.strokeWidth
                    });
                }
                
                layer.properties = data.properties;
                layer.addTo(exportMap);
                updateLayerTooltip(layer);
            });
            
            // 等待地图加载完成
            setTimeout(() => {
                // 调整地图视图，确保所有要素都在可见区域内
                if (drawnLayers.getLayers().length > 0) {
                    exportMap.fitBounds(drawnLayers.getBounds(), { padding: [50, 50] });
                }
                
                // 使用html2canvas捕获地图
                html2canvas(exportContainer, {
                    scale: 2, // 提高分辨率
                    useCORS: true,
                    logging: false
                }).then(canvas => {
                    // 创建PDF
                    const { jsPDF } = window.jspdf;
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    
                    // 计算比例，使地图适应A4页面
                    const imgData = canvas.toDataURL('image/png');
                    const imgWidth = 210;
                    const imgHeight = canvas.height * imgWidth / canvas.width;
                    
                    // 添加图像到PDF
                    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
                    
                    // 保存PDF
                    pdf.save('地块地图.pdf');
                    
                    // 清理临时容器
                    document.body.removeChild(exportContainer);
                    
                    // 恢复原始地图视图
                    map.setView(currentCenter, currentZoom);
                });
            }, 1000);
        }

        // 初始加载
        (function() {
            // 默认加载一次图片，使其在切换到图片模式时立即可见
            loadImageView(document.getElementById('image-url').value);
            // 立即切回天地图模式作为默认视图
            switchMode('tianditu');
             if(imageLayer) map.removeLayer(imageLayer); // 隐藏图片层
        })();
    </script>
</body>
</html>